package com.nondo.rdp.finance.endpoint.api.app;

import com.nondo.rdp.auth.common.UserUtils;
import com.nondo.rdp.auth.domain.PointsLog;
import com.nondo.rdp.auth.domain.User;
import com.nondo.rdp.auth.endpoint.model.ConvertCall;
import com.nondo.rdp.auth.endpoint.model.Page;
import com.nondo.rdp.auth.endpoint.model.Query;
import com.nondo.rdp.auth.event.PointApplicationEvent;
import com.nondo.rdp.auth.listener.PointApplicationListener;
import com.nondo.rdp.auth.service.PointsLogService;
import com.nondo.rdp.auth.service.UserService;
import com.nondo.rdp.core.common.BeanUtils;
import com.nondo.rdp.core.common.CommUtil;
import com.nondo.rdp.core.model.View;
import com.nondo.rdp.finance.common.DateProcessUtils;
import com.nondo.rdp.finance.domain.log.SignLog;
import com.nondo.rdp.finance.model.SignLogBean;
import com.nondo.rdp.finance.service.log.SignLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController("apiAppSignLog")
@RequestMapping("/api/app/sign")
public class SignEndpoint {
    @Autowired
    SignLogService signLogService;

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    @Autowired
    UserService userService;

    @Autowired
    PointsLogService pointsLogService;

    @RequestMapping("/list")
    public View<Page> list(HttpServletRequest request, HttpServletResponse response, @RequestBody Query<SignLog> query) {
        View<Page> view = new View(20000, "获取列表成功");

        User user = UserUtils.getUser(request, response);

        SignLog signLog = query.getData();
        signLog.setUser(user);

        Page<SignLog> page = signLogService.findAll(new Page<SignLog>(query.getPage(), query.getSize()), signLog);

        Page<SignLogBean> resultPage = page.convertPage(new ConvertCall<SignLog, Page<SignLogBean>>() {
            @Override
            public Page<SignLogBean> execute(Page<SignLog> srcPage) {
                Page<SignLogBean> signLogBeanPage = new Page<SignLogBean>(srcPage.getPageNumber(), srcPage.getPageSize(), srcPage.getTotalPages(), srcPage.getTotalElements());
                //处理数据
                List<SignLogBean> list = new ArrayList<SignLogBean>();
                for (Object item : srcPage.getContent()) {
                    SignLogBean signLogBean = new SignLogBean();
                    BeanUtils.copy(item, signLogBean);

                    //处理返回日期
                    signLogBean.setCreateDateString(CommUtil.dateFormat(signLogBean.getCreateDate(), "YYYY-MM-dd"));

                    list.add(signLogBean);
                }
                signLogBeanPage.setContent(list);

                return signLogBeanPage;
            }
        });

        view.setData(resultPage);

        return view;
    }

    @RequestMapping("/list/month")
    public View listMonth(HttpServletRequest request, HttpServletResponse response) {
        View view = new View(20000, "获取成功");
        User user = UserUtils.checkUser();

        //获取一个月的开始结束时间
        Date monthStartTime = DateProcessUtils.getCurrentMonthStartTime();
        Date monthEndTime = DateProcessUtils.getCurrentMonthEndTime();

        //获取本月第一天是星期几
        Calendar cal = Calendar.getInstance(); // 获得一个日历
        cal.setTime(monthStartTime);
        int w = cal.get(Calendar.DAY_OF_WEEK);//由于是国外的展示，我们这里又需要获取前面空白了几日，所以需要减去2天
        System.out.println(w);

        //获取一个月的时间日历表
        List list = CommUtil.getAllDaysMonth();
        Map cadList = new HashMap();
        for (int i = 0; i < w - 1; i++) {
            cadList.put(i, new HashMap());
        }
        for (int i = 0; i < list.size(); i++) {
            Map map = new HashMap();
            map.put("day", list.get(i));
            map.put("sign", 0);
            cadList.put(i + w - 1, map);
        }

        int totalSign = 0;

        if (user.getId() != null) {
            //获取本月的签到日历
            List<SignLog> monthSignList = this.signLogService.findByUserAndCreateDateBetween(user, monthStartTime, monthEndTime);

            //循环处理本月的签到日历

            for (SignLog item : monthSignList) {
                String dateKey = CommUtil.dateFormat(item.getCreateDate(), "d");
                Map map = new HashMap();
                map.put("day", Integer.parseInt(dateKey));
                map.put("sign", 1);
                cadList.put(Integer.parseInt(dateKey) + w - 2, map);
                //签到增加一天
                totalSign++;
            }
        }

        Map returnData = new HashMap();
        returnData.put("list", cadList);
        returnData.put("totalSign", totalSign);

        //判断今天是否已经签到
        if (user.getId() != null) {
            Date todayStartTime = CommUtil.getTodayZeroTime();
            SignLog todaySing = this.signLogService.findByUserAndCreateDateAfter(user, todayStartTime);
            if (todaySing == null) {
                returnData.put("isSignTody", 0);
            } else {
                returnData.put("isSignTody", 1);
            }
        } else {
            returnData.put("isSignTody", 0);
        }


        view.setData(returnData);

        return view;
    }

    @RequestMapping("/in")
    public View singIn(HttpServletRequest request, HttpServletResponse response) {
        User user = UserUtils.getUser(request, response);

        //判断今天是否已经签到了
        Date todayStartTime = CommUtil.getTodayZeroTime();
        SignLog todaySing = this.signLogService.findByUserAndCreateDateAfter(user, todayStartTime);
        if (todaySing != null) {
            return View.ofError("今天已经签过到了");
        }

        //查询之前签到的天数
        Date yesterdayStartTime = DateProcessUtils.getYesterdayStartTime();
        Date yesterdayEndTime = DateProcessUtils.getYesterdayEndTime();
        List<SignLog> yesterdaySign = this.signLogService.findByUserAndCreateDateBetween(user, yesterdayStartTime, yesterdayEndTime);
        int signDays = 1;
        if (yesterdaySign.size() > 0) {
            for (SignLog item : yesterdaySign) {
                //此处只查询一天的
                signDays = item.getDays() + 1;
                break;
            }
        }

        //保存为新的天数
        SignLog signLog = new SignLog();
        signLog.setUser(user);
        signLog.setDays(signDays);
        this.signLogService.save(signLog);

        //调用积分事件
        applicationEventPublisher.publishEvent(new PointApplicationEvent(this, user, PointApplicationListener.TYPE_SIGN));

        /**
         * 活动功能，签到多少天赠送多少积分
         */
        Date monthStartTime = DateProcessUtils.getCurrentMonthStartTime();
        Date monthEndTime = DateProcessUtils.getCurrentMonthEndTime();
        List<SignLog> monthSignList = this.signLogService.findByUserAndCreateDateBetween(user, monthStartTime, monthEndTime);
        long point = 0;
        switch (monthSignList.size()) {
            case 1:
                point = 10;
                break;
            case 7:
                point = 10;
                break;
            case 15:
                point = 10;
                break;
            case 25:
                point = 10;
                break;
        }
        if (monthSignList.size() == 1 || monthSignList.size() == 7 || monthSignList.size() == 15 || monthSignList.size() == 25) {
            long lastPoints = user.getPoints() + point;
            //增加积分日志
            user.setPoints(lastPoints);
            this.userService.save(user);
            PointsLog pointsLog = new PointsLog();
            pointsLog.setPoints(point);
            pointsLog.setUserId(user.getId());
            pointsLog.setLastPoints(lastPoints);
            this.pointsLogService.save(pointsLog);
        }

        return View.ofOk("签到成功");
    }
}